'''
Created on 2014-2-24

@author: apple
'''
from com.ad.sword.web.pages import app

'''
Created on 2014-2-5

@author: apple
'''
from com.ad.sword.web.common import *
from com.ad.sword.dao.models import HttpTask,MonitorTask
import math
from urlparse import urlparse
from django.db.utils import IntegrityError

def info(request):
    id= request.REQUEST.get('id', None)
    if id:
        task=MonitorTask.objects.get(id=id)
        httpTask=HttpTask.objects.get(task=task)    
        t={}
        for k in task:
            if k=='create_time':
                t[k]=time2str(task[k])
            else:
                t[k]=str(task[k])
        for k in httpTask:
            t[k]=str(task[k])
        return template("app/appInfo.html",t)
    else:
        return template("app/appInfo.html")



@check_required_argument
def update(request):
    from django.db import IntegrityError
    id= request.REQUEST.get('id', None)
    if id:
        baseTask=MonitorTask.objects.get(id=id)
        httpTask=HttpTask.objects.get(task=baseTask)
    else:
        httpTask=HttpTask()
        httpTask.result=7
        
        baseTask =MonitorTask()
        baseTask.type='0'
        baseTask.status='E'
        baseTask.create_time=datetime.now()
    baseTask.name=get_required_argument(request, "name")
    baseTask.desc=get_required_argument(request, "desc")
    baseTask.frequency=int(get_required_argument(request, "frequency"))

    
    httpTask.url=get_required_argument(request, "url")
    httpTask.alarm_policy=int(get_required_argument(request, "alarm_policy"))
    httpTask.notify_types=get_required_argument(request, "notify_types").split(',')
    baseTask.ip=urlparse(httpTask.url)[1]
    httpTask.task=baseTask
    
    try:
        baseTask.save()
        httpTask.save(cascade=True)
    except IntegrityError:
        return message("Error")
    request.log.Info(title=_("Update HTTP Monitor Task"),description=_("Update HTTP Monitor Task %s") % baseTask.name);
    return app(request)


@tojson
@check_login
def flipTask(request):
    id=get_required_argument(request, "id")
    task=MonitorTask.objects.get(id=id)
    task.status=get_required_argument(request, "status")
    try:
        
        task.save()
    except IntegrityError:
        return message("Error")
    request.log.Info(title=_("filp HTTP Monitor Task"),description=_("filp HTTP Monitor Task %s") % task.name);
    return message("OK")

